package com.hundsun.fcp.openapi;

import java.lang.reflect.Type;
import java.net.SocketTimeoutException;

import org.apache.http.Header;
import org.apache.http.client.HttpResponseException;
import org.apache.http.conn.ConnectTimeoutException;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.hundsun.fcp.common.logger.AndroidLogger;
import com.hundsun.fcp.common.logger.Logger;
import com.hundsun.fcp.common.utils.ObjectUtil;
import com.hundsun.fcp.openapi.trade.bean.Result;
import com.hundsun.fcp.webplugin.service.ErrorCode;
import com.loopj.android.http.RequestParams;

public abstract class OpenApiDataServiceBase extends DataServiceBase {
	private static final Logger LOGGER = AndroidLogger.getLogger() ;
	private IOpenApiDataServiceCallback callback ;
	private Context mContext ;
	public OpenApiDataServiceBase(Context pContext){
		super() ;
		mContext = pContext ;
	}
	
	/**
	 * get 请求
	 * @param pObject
	 */
	public void get(Object entity){
		RequestParams _Params =  null ;
		if(entity!=null){
			_Params = ObjectUtil.convertToRequestParams(entity) ;
		}
		httpClient.get(getRequestURL(),_Params , this) ;
		
	}
	
	/**
	 * post 请求
	 * @param pObject
	 */
	public void post(Object entity){
		RequestParams _Params =  null ;
		if(entity!=null){
			_Params = ObjectUtil.convertToRequestParams(entity) ;
		}
		httpClient.post(getRequestURL(), _Params, this) ;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
		try {
			if (callback != null) {
				String responseStr = new String(responseBody, "utf-8") ;
				LOGGER.debug("onSuccess:"+responseStr) ;
				/**
				 * 对结果进行json 处理
				 */
				Object resultClass = getDataBeanTypeOrClass() ;
				
				if(resultClass instanceof Class){
					Result object = JSON.parseObject(responseStr, (Class<Result>)resultClass) ;
					callback.onGetData(object);
				}
			}
		} catch (Exception e) {
			LOGGER.debug("数据处理异常", e) ;
			HandleError(ErrorCode.ON_SUCCESS_ERROR, e.getMessage(), e);
		}

	}

	@Override
	public void onFailure(int statusCode, Header[] headers,
			byte[] responseBody, Throwable error) {
		int _ErrorCode = ErrorCode.SOCKET_ERROR ;
		try{
			
		    if (error instanceof HttpResponseException) {
		    	_ErrorCode = ((HttpResponseException)error).getStatusCode();
		    }
		    
		    if(error instanceof SocketTimeoutException){
		    	_ErrorCode = ErrorCode.SOCKET_TIMEOUT ;
		    }
		    
		    if(error instanceof ConnectTimeoutException){
		    	_ErrorCode = ErrorCode.CONNECT_TIMEOUT ;
		    }

		    String errorMsg = new String(responseBody);
			
		    HandleError(_ErrorCode, errorMsg==null?"":errorMsg, error);
		    
		}catch(Exception e){
			 HandleError(_ErrorCode, "网络连接连接错误", error);
		}
	}
	
	/**请求的地址*/
	protected abstract String getResouceURI();
	/**bean class 用于json 转换*/
	protected abstract Object getDataBeanTypeOrClass();

	public IOpenApiDataServiceCallback getCallback() {
		return callback;
	}

	public void setCallback(IOpenApiDataServiceCallback callback) {
		this.callback = callback;
	}
	
	public void HandleError(int errorCode, String errorMsg,
			Throwable errorThrowable) {
		try {
			LOGGER.debug("HandleError:"+errorMsg) ;
			if (callback!= null) {
				callback.onGetError(errorCode, errorMsg, errorThrowable);
			}
		} catch (Exception e) {
			LOGGER.debug("HandleError", e);
		}
	}

	
	public void cancel() {
		if(httpClient!=null){
			httpClient.cancelRequests(mContext, true) ;
		}
	}
	
	/**
	 * 网路请求地址
	 * @return
	 */
	private String getRequestURL(){
		String _ApiUrl = getApiURL() ;
		String _ResoureUrl = getResouceURI() ;
		return _ApiUrl + _ResoureUrl ;
	}
	
	/**
	 * 总的请求地址
	 * @return
	 */
	private String getApiURL() {
		return "http://192.168.236.20:8080/epc/" ;
	}
}
